package manager.utils;

import manager.resp.RespData;
import manager.resp.StateCodeDesc;

import java.io.*;
import java.net.Socket;

/**
 * @author shidang.hu
 */
public class FileOperateUtils {

    /**
     * 需要加解密
     */
    private static final String ENCRYPT_FLAG_Y = "Y";

    public static boolean HandleUpload(String fileFullPath, FileOutputStream fos, DataInputStream dis, String encryptFlag,String encryptKey){
        if(ENCRYPT_FLAG_Y.equals(encryptFlag)){
           return processUploadEncrypt(fileFullPath, fos, dis, encryptKey);
        }
        return processUpload(fileFullPath, fos, dis);
    }

    public static boolean HandleDownload(String filePath, Socket sock, String encryptFlag,String encryptKey){
        if(ENCRYPT_FLAG_Y.equals(encryptFlag)){
            return processDownloadDecypt(filePath, sock, encryptKey);
        }
        return processDownload(filePath, sock);
    }

    public static boolean processUpload(String fileFullPath, FileOutputStream fos, DataInputStream dis) {
        File file = new File(fileFullPath);
        String parentDir = file.getParent();
        // 父文件夹不存在，创建一个
        File dir = new File(parentDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            //文件存储路径
            fos = new FileOutputStream(new File(fileFullPath));
            byte[] sendBytes = new byte[1024];
            while (true) {
                int read = 0;
                read = dis.read(sendBytes);
                if (read == -1) {
                    break;
                }
                fos.write(sendBytes, 0, read);
                fos.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException("处理上传文件信息异常：" + e.getMessage());
        } finally {
            // 关流（谁使用，谁关闭）
            try {
                if (dis != null) {
                    dis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public static boolean processUploadEncrypt(String fileFullPath, FileOutputStream fos, DataInputStream dis, String encryptKey) {
        File file = new File(fileFullPath);
        String parentDir = file.getParent();

        // 父文件夹不存在，创建一个
        File dir = new File(parentDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            int secret = Integer.parseInt(encryptKey);
            //文件存储路径
            fos = new FileOutputStream(new File(fileFullPath));
//            byte[] sendBytes = new byte[1024];
            int data=-1;
            while ((data = dis.read()) > -1) {
                fos.write(data + secret);
            }
            fos.flush();
        } catch (Exception e) {
            throw new RuntimeException("处理上传文件信息异常：" + e.getMessage());
        } finally {
            // 关流（谁使用，谁关闭）
            try {
                if (dis != null) {
                    dis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    public static boolean processDownload(String filePath, Socket sock) {

        // 判断文件路径是否存在
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new RuntimeException("文件不存在");
        }
        InputStream fis = null;
        DataOutputStream output = null;
        // 将文件写出给客户端
        try {
            output = new DataOutputStream(sock.getOutputStream());
            output.writeUTF(file.getName());
            output.flush();
            output.writeLong(file.length());
            output.flush();
            // 从磁盘读文件
            fis = new BufferedInputStream(new FileInputStream(file));
            //接收数据的缓存
            byte[] buf = new byte[1024];
            while (true) {
                int read = 0;
                if (fis != null) {
                    read = fis.read(buf);
                }

                if (read == -1) {
                    break;
                }
                output.write(buf, 0, read);
            }
            output.flush();
        } catch (Exception e) {
            throw new RuntimeException("处理下载文件异常：" + e.getMessage());
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public static boolean processDownloadDecypt(String filePath, Socket sock, String encryptKey) {

        // 判断文件路径是否存在
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new RuntimeException("文件不存在");
        }
        InputStream fis = null;
        DataOutputStream output = null;
        // 将文件写出给客户端
        try {
            int secret = Integer.parseInt(encryptKey);

            output = new DataOutputStream(sock.getOutputStream());
            output.writeUTF(file.getName());
            output.flush();
            output.writeLong(file.length());
            output.flush();
            // 从磁盘读文件
            fis = new BufferedInputStream(new FileInputStream(file));
            //接收数据的缓存
            int data = -1;
            while ((data = fis.read()) > -1) {
                output.write(data - secret);
            }
            output.flush();
        } catch (Exception e) {
            throw new RuntimeException("处理下载文件异常：" + e.getMessage());
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
